<?php

namespace app\controllers;

use app\models\User;
use cccmvc\Application;
use cccmvc\exception\AuthException;
use cccmvc\exception\DatabaseException;
use cccmvc\Request;
use cccmvc\View;

class UserController
{
    public function index()
    {
        $userid = Application::$app->session->get('userid');

        if (!$userid) {
            Application::$app->response->redirect('/');
        }

        $user = new User($userid);

        return View::render('profile', ['username' => $user->username]);
    }

    public function login()
    {
        if ($this->isAuthed())
            Application::$app->response->redirect('/user');

        return View::render('login');
    }

    public function register()
    {
        if ($this->isAuthed())
            Application::$app->response->redirect('/user');

        return View::render('register');
    }

    public function logout(): void
    {
        Application::$app->session->remove('userid');
        Application::$app->response->redirect('/');
    }

    public function doLogin(Request $request)
    {
        $user = new User();
        $user = $user->getUserData(['email' => $request->input('email')]);
        $password = $request->input('password', '');

        try {
            if (!$user->id()) {
                throw new AuthException('Invalid user or password!');
            }

            if (password_verify($password, $user->password)) {
                Application::$app->session->set('userid', $user->id);
                Application::$app->response->redirect('/user');
            }

            throw new AuthException('Invalid user or password!');
        } catch (AuthException $e) {
            return View::render('login', ['error' => $e->getMessage()]);
        }


    }

    public function doRegister(Request $request)
    {
        $user = new User();

        try {
            $data = $request->all();

            if (!$data['email'] || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
                throw new AuthException('Invalid email!');
            }

            if (!$data['username'] || !preg_match('/^[A-Za-z]{1}[A-Za-z0-9_-]{6,15}$/', $data['username'])) {
                throw new AuthException('Invalid username! Please enter 6-15 letters or numbers.');
            }

            if (!$data['password'] || !preg_match('/^[A-Za-z\d]{6,15}$/', $data['password'])) {
                throw new AuthException('Invalid password! Length: 6-15');
            }

            if ($data['password'] !== $data['confirm_password']) {
                throw new AuthException('The two passwords are different!');
            }

            $user->create($data);

            if (!$user->id()) {
                throw new AuthException('Server error!');
            }

            Application::$app->session->set('userid', $user->id());

            Application::$app->response->redirect('/user');
        } catch (AuthException | DatabaseException $e) {
            $msg = $e->getMessage();

            if ($e->getCode() === 1062) {
                $msg = 'Username or email already exists!';
            }

            return View::render('register', array_merge(['error' => $msg], $data));
        }
    }

    private function isAuthed()
    {
        return !!Application::$app->session->get('userid');
    }
}